<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
      style="border-bottom: 1px solid #ccc"
      :editor="editorRef"
      :defaultConfig="toolbarConfig"
    />
    <Editor
      style="height: 500px; overflow-y: hidden"
      v-model="valueHtml"
      :defaultConfig="editorConfig"
      @onCreated="handleCreated"
    />
  </div>
</template>

<script setup>
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, ref, shallowRef, watchEffect, watch, onMounted } from 'vue'
import { Editor, Toolbar } from '@wangeditor/editor-for-vue'
import { upload } from '@/api/uploadFile'
import { ElMessage } from 'element-plus'
import { serverStore } from '@/stores/server'
import { decryptData } from '@/utils/CryptoJSUtil'

// 声明属性
const props = defineProps({
  modelValue: {
    type: String,
    default: '',
  },
})

// 声明事件消息
const emits = defineEmits()

// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef()

// 内容 HTML
const valueHtml = ref('')
// 当属性变化时，自动赋值给 valueHtml
watchEffect(() => {
  /**
   * 监听 props.modelValue
   */
  valueHtml.value = props.modelValue
})
// 当 watchHtml 变化时，自动告诉父组件
watch(valueHtml, (newHtml) => {
  emits('update:modelValue', newHtml)
})

// 获取服务器上传地址
const { serverUploadImg } = serverStore()

const toolbarConfig = {}
const editorConfig = {
  placeholder: '请输入文章内容...',
  MENU_CONF: {
    uploadImage: {
      server: serverUploadImg,
      fieldName: 'file',
      headers: {
        token: localStorage.getItem('token'),
      },
      customInsert(res, insertFn) {
        console.log(res)
        if (res && typeof res === 'string') {
          try {
            const decrypted = decryptData(res)
            const url = JSON.parse(decrypted).msg
            insertFn(url)
          } catch (err) {
            console.error('解密响应失败:', err)
          }
        }
      },
    },
  },
}

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

const handleCreated = (editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>